package com.dodayum.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dodayum.dao.TaskAddRemarkDTO;
import com.dodayum.entity.TaskEntity;
import com.dodayum.mapper.TaskMapping;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class TaskService {

    @Resource
    TaskMapping taskMapping;

    public List<TaskEntity> query(String sourceType) {
        Date earliestUnfinishedTime = taskMapping.queryEarliestUnfinishedTime();


        Page<TaskEntity> page = new Page<>(1, 10);
        LambdaQueryWrapper<TaskEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(StringUtils.isNotBlank(sourceType), TaskEntity::getSource, sourceType)
                .ge(!ObjectUtils.isEmpty(earliestUnfinishedTime), TaskEntity::getCreateTime, earliestUnfinishedTime)
                .orderByAsc(TaskEntity::getCreateTime);
        Page<TaskEntity> taskEntityPage = taskMapping.selectPage(page, queryWrapper);
        return taskEntityPage.getRecords();
    }

    public void create(TaskEntity request) {
        Date date = new Date();
        request.setCreateTime(date);
        request.setUpdateTime(date);
        taskMapping.insert(request);
    }

    public void updateStatus(Integer id) {
        TaskEntity taskEntity = taskMapping.selectById(id);
        taskEntity.setStatus(Boolean.TRUE);
        taskEntity.setUpdateTime(new Date());
        taskMapping.updateById(taskEntity);
    }

    public void addRemark(TaskAddRemarkDTO request) {
        TaskEntity taskEntity = taskMapping.selectById(request.getId());
        List<String> remark = taskEntity.getRemarkAsList();
        remark.add(request.getRemark());
        taskEntity.setRemarkFromList(remark);
        taskEntity.setUpdateTime(new Date());
        taskMapping.updateById(taskEntity);
    }

    public List<String> queryAllSource() {
        return taskMapping.queryAllSource();
    }

    public TaskEntity queryById(Integer id) {
        return taskMapping.selectById(id);
    }
}
